// 创建整个应用的路由器
import VueRouter from "vue-router";

// 导入组件
import Home from '../pages/Home.vue';
import Login from '../pages/Login.vue';
import Music from '../pages/Music.vue';
import Film from '../pages/Film.vue';
import PersonInfo from '../pages/PersonInfo.vue';
import Erorr from '../pages/Error.vue';
import axios from "axios";

// 创建一个路由
let router = new VueRouter({
    mode: 'history',
    // 一组路由
    routes: [
        {
            path: '/',
            redirect: '/login'
        },
        {
            path: '/login',
            name: 'Login',
            component: Login
        },
        {
            path: '/home', // 配置路由访问路径
            name: 'Home', // 给路由取名字
            component: Home, // 配置路由组件
            children: [ // 配置多个子组建，语法与父组件的语法一样
                {
                    path: '/home/music',
                    name: 'music',
                    component: Music
                },
                {
                    path: '/home/film',
                    name: 'film',
                    component: Film
                },
                {
                    path: '/home/personinfo',
                    name: 'personinfo',
                    component: PersonInfo
                }
            ]
        },
        {
            path: '/error',
            name: 'error',
            component: Erorr
        }
    ],
});
router.beforeEach((to,from,next)=>{ // 设置路由跳转认证
    if(to.path.startsWith('/login')) { // 匹配无需校验就可以放行的路由
        console.log('222222')
        window.localStorage.removeItem('access-admin'); // 提前移除指定的token存储键
        next(); // 路由放行
    }else {
        const admin = JSON.parse(window.localStorage.getItem('access-admin'));
        if(!admin) {
            next({path: '/login'}); // 指定路由跳转路径
        }else{
            // 校验token的合法性
            axios({
                url: 'http://localhost:8081/checkToken', // 设置请求地址
                method: 'get', // 请求方式
                headers: { // 设置请求头信息
                    token: admin.token
                }
            }).then((response)=>{
                if(!response.data) {
                    console.log('校验失败');
                    next({path: '/error'})
                }
            });
            next(); // 正常情况直接放行
        }
    }
});
// 暴露路由
export default router;